/*
 * 22/10/2011 - 12:15
 */
package org.nettyflux.tcp;

import java.io.BufferedInputStream;
import java.io.IOException;

/**
 * @author Victor Williams Stafusa da Silva
 */
class SimpleByteBuffer {

    private byte[] bytes;

    public SimpleByteBuffer() {
        this.bytes = new byte[0];
    }

    public void append(byte[] moreBytes) {
        int newLength = bytes.length + moreBytes.length;
        byte[] newBuffer = new byte[newLength];
        System.arraycopy(bytes, 0, newBuffer, 0, bytes.length);
        System.arraycopy(moreBytes, 0, newBuffer, bytes.length, moreBytes.length);
        this.bytes = newBuffer;
    }

    public void appendAvailable(BufferedInputStream bis) throws IOException {
        while (true) {
            byte[] buf = new byte[65536];
            int r = bis.read(buf);
            if (r <= 0) return;
            byte[] newBuffer = new byte[bytes.length + r];
            System.arraycopy(bytes, 0, newBuffer, 0, bytes.length);
            System.arraycopy(buf, 0, newBuffer, bytes.length, r);
            this.bytes = newBuffer;
        }
    }

    public byte[] getBytes() {
        return bytes;
    }
}
